'use strict';

const Service = require('egg').Service;

class AIAnalysisService extends Service {
  
  // 获取大模型配置
  getAIConfig() {
    return this.config.ai || {
      provider: 'doubao', // local, qianwen, deepseek, doubao, vapi, openai, zhipu, ollama
      apiKey: 'your_api_key',
      baseURL: 'https://api.openai.com/v1',
      model: 'gpt-3.5-turbo',

      // 免费AI服务配置
      qianwenApiKey: 'your_qianwen_key', // 通义千问
      deepseekApiKey: 'your_deepseek_key', // DeepSeek
      doubaoApiKey: '97fef7f1-56e5-4290-978c-9072c918df67', // 火山引擎豆包
      vapiKey: 'your_vapi_key', // V-API聚合
      vapiBaseURL: 'https://api.v-api.cn/v1', // V-API地址

      // 本地AI配置
      localModel: 'fashion-advisor',
      ollamaHost: 'http://localhost:11434',
      huggingfaceModel: 'microsoft/DialoGPT-medium'
    };
  }

  // 调用OpenAI API
  async callOpenAI(messages, options = {}) {
    const config = this.getAIConfig();
    
    try {
      const response = await this.ctx.curl(`${config.baseURL}/chat/completions`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${config.apiKey}`,
          'Content-Type': 'application/json'
        },
        data: {
          model: config.model || 'gpt-3.5-turbo',
          messages,
          max_tokens: options.maxTokens || 1000,
          temperature: options.temperature || 0.7
        },
        dataType: 'json',
        timeout: 30000
      });

      if (response.status === 200 && response.data.choices?.[0]?.message?.content) {
        return response.data.choices[0].message.content;
      } else {
        throw new Error('OpenAI API调用失败');
      }
    } catch (error) {
      console.error('OpenAI API调用错误:', error);
      throw error;
    }
  }

  // 调用通义千问API（免费额度）
  async callQianwen(messages, options = {}) {
    const config = this.getAIConfig();
    const apiKey = config.qianwenApiKey || config.apiKey;

    try {
      const response = await this.ctx.curl('https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${apiKey}`,
          'Content-Type': 'application/json'
        },
        data: {
          model: 'qwen-turbo', // 免费模型
          input: {
            messages
          },
          parameters: {
            max_tokens: options.maxTokens || 1000,
            temperature: options.temperature || 0.7
          }
        },
        dataType: 'json',
        timeout: 30000
      });

      if (response.status === 200 && response.data.output?.text) {
        return response.data.output.text;
      } else {
        throw new Error('通义千问API调用失败');
      }
    } catch (error) {
      console.error('通义千问API调用错误:', error);
      throw error;
    }
  }

  // 调用DeepSeek API（免费额度）
  async callDeepSeek(messages, options = {}) {
    const config = this.getAIConfig();
    const apiKey = config.deepseekApiKey || config.apiKey;

    console.log(`🌐 DeepSeek API调用开始...`);
    console.log(`🔑 使用API密钥: ${apiKey.substring(0, 10)}...`);
    console.log(`📨 消息数量: ${messages.length}`);

    try {
      const requestData = {
        model: 'deepseek-chat', // 免费模型
        messages,
        max_tokens: options.maxTokens || 1000,
        temperature: options.temperature || 0.7
      };

      console.log(`📤 请求数据:`, {
        model: requestData.model,
        messagesCount: requestData.messages.length,
        maxTokens: requestData.max_tokens,
        temperature: requestData.temperature
      });

      const response = await this.ctx.curl('https://api.deepseek.com/v1/chat/completions', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${apiKey}`,
          'Content-Type': 'application/json'
        },
        data: requestData,
        dataType: 'json',
        timeout: 30000
      });

      console.log(`📥 DeepSeek响应状态: ${response.status}`);
      console.log(`📥 响应数据:`, response.data);

      if (response.status === 200 && response.data.choices?.[0]?.message?.content) {
        const content = response.data.choices[0].message.content;
        console.log(`✅ DeepSeek API调用成功，响应长度: ${content.length}`);
        return content;
      } else {
        console.error('❌ DeepSeek API响应格式错误:', response.data);
        throw new Error(`DeepSeek API调用失败: ${JSON.stringify(response.data)}`);
      }
    } catch (error) {
      console.error('❌ DeepSeek API调用错误:', error.message);
      console.error('❌ 错误详情:', error);
      throw error;
    }
  }

  // 调用豆包API（原始豆包）
  async callDoubao(messages, options = {}) {
    const config = this.getAIConfig();
    const apiKey = config.doubaoApiKey || config.apiKey;

    console.log(`🥟 豆包API调用开始...`);
    console.log(`🔑 使用API密钥: ${apiKey.substring(0, 10)}...`);
    console.log(`📨 消息数量: ${messages.length}`);

    try {
      const requestData = {
        model: 'doubao-lite-4k', // 豆包免费模型
        messages,
        max_tokens: options.maxTokens || 1000,
        temperature: options.temperature || 0.7,
        stream: false
      };

      console.log(`📤 请求数据:`, {
        model: requestData.model,
        messagesCount: requestData.messages.length,
        maxTokens: requestData.max_tokens,
        temperature: requestData.temperature
      });

      const response = await this.ctx.curl('https://ark.cn-beijing.volces.com/api/v3/chat/completions', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${apiKey}`,
          'Content-Type': 'application/json'
        },
        data: requestData,
        dataType: 'json',
        timeout: 30000
      });

      console.log(`📥 豆包响应状态: ${response.status}`);
      console.log(`📥 响应数据:`, response.data);

      if (response.status === 200 && response.data.choices?.[0]?.message?.content) {
        const content = response.data.choices[0].message.content;
        console.log(`✅ 豆包API调用成功，响应长度: ${content.length}`);
        return content;
      } else {
        console.error('❌ 豆包API响应格式错误:', response.data);
        throw new Error(`豆包API调用失败: ${JSON.stringify(response.data)}`);
      }
    } catch (error) {
      console.error('❌ 豆包API调用错误:', error.message);
      console.error('❌ 错误详情:', error);
      throw error;
    }
  }

  // 调用火山引擎火山方舟API
  async callVolcano(messages, options = {}) {
    const config = this.getAIConfig();
    const apiKey = config.volcanoApiKey || config.apiKey;
    const endpoint = config.volcanoEndpoint || 'ep-m-20250724225547-7twv8';
    const model = config.volcanoModel || 'deepseek-r1-250528';

    console.log(`🌋 火山引擎API调用开始...`);
    console.log(`🔑 使用API密钥: ${apiKey.substring(0, 10)}...`);
    console.log(`🎯 端点ID: ${endpoint}`);
    console.log(`🤖 模型: ${model}`);
    console.log(`📨 消息数量: ${messages.length}`);

    try {
      const requestData = {
        model: endpoint, // 火山方舟使用端点ID作为模型参数
        messages,
        max_tokens: options.maxTokens || 1000,
        temperature: options.temperature || 0.7,
        stream: false
      };

      console.log(`📤 请求数据:`, {
        model: requestData.model,
        messagesCount: requestData.messages.length,
        maxTokens: requestData.max_tokens,
        temperature: requestData.temperature
      });

      const response = await this.ctx.curl('https://ark.cn-beijing.volces.com/api/v3/chat/completions', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${apiKey}`,
          'Content-Type': 'application/json'
        },
        data: requestData,
        dataType: 'json',
        timeout: 240000, // 增加到4分钟
        retry: 2, // 重试2次
        retryDelay: 1000 // 重试间隔1秒
      });

      console.log(`📥 火山引擎响应状态: ${response.status}`);
      console.log(`📥 响应数据:`, response.data);

      if (response.status === 200 && response.data.choices?.[0]?.message?.content) {
        const content = response.data.choices[0].message.content;
        console.log(`✅ 火山引擎API调用成功，响应长度: ${content.length}`);
        console.log(`📄 AI完整响应内容:`, content.substring(0, 500) + '...');
        return content;
      } else {
        console.error('❌ 火山引擎API响应格式错误:', response.data);
        throw new Error(`火山引擎API调用失败: ${JSON.stringify(response.data)}`);
      }
    } catch (error) {
      console.error('❌ 火山引擎API调用错误:', error.message);
      console.error('❌ 错误详情:', error);
      throw error;
    }
  }

  // 调用V-API聚合服务（多模型聚合）
  async callVAPI(messages, options = {}) {
    const config = this.getAIConfig();
    const apiKey = config.vapiKey || config.apiKey;
    const baseURL = config.vapiBaseURL || 'https://api.v-api.cn/v1';

    try {
      const response = await this.ctx.curl(`${baseURL}/chat/completions`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${apiKey}`,
          'Content-Type': 'application/json'
        },
        data: {
          model: 'gpt-3.5-turbo', // V-API支持多种模型
          messages,
          max_tokens: options.maxTokens || 1000,
          temperature: options.temperature || 0.7
        },
        dataType: 'json',
        timeout: 30000
      });

      if (response.status === 200 && response.data.choices?.[0]?.message?.content) {
        return response.data.choices[0].message.content;
      } else {
        throw new Error('V-API调用失败');
      }
    } catch (error) {
      console.error('V-API调用错误:', error);
      throw error;
    }
  }

  // 调用智谱AI API
  async callZhipu(messages, options = {}) {
    const config = this.getAIConfig();

    try {
      const response = await this.ctx.curl('https://open.bigmodel.cn/api/paas/v4/chat/completions', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${config.apiKey}`,
          'Content-Type': 'application/json'
        },
        data: {
          model: config.model || 'glm-4',
          messages,
          max_tokens: options.maxTokens || 1000,
          temperature: options.temperature || 0.7
        },
        dataType: 'json',
        timeout: 30000
      });

      if (response.status === 200 && response.data.choices?.[0]?.message?.content) {
        return response.data.choices[0].message.content;
      } else {
        throw new Error('智谱AI API调用失败');
      }
    } catch (error) {
      console.error('智谱AI API调用错误:', error);
      throw error;
    }
  }

  // 调用Ollama本地模型（完全免费）
  async callOllama(messages, options = {}) {
    const config = this.getAIConfig();
    const ollamaHost = config.ollamaHost || 'http://localhost:11434';

    try {
      // 转换消息格式为Ollama格式
      const prompt = messages.map(msg => `${msg.role}: ${msg.content}`).join('\n');

      const response = await this.ctx.curl(`${ollamaHost}/api/generate`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        data: {
          model: config.model || 'llama2',
          prompt,
          stream: false,
          options: {
            temperature: options.temperature || 0.7,
            num_predict: options.maxTokens || 1000
          }
        },
        dataType: 'json',
        timeout: 240000 // Ollama可能需要更长时间
      });

      if (response.status === 200 && response.data.response) {
        return response.data.response;
      } else {
        throw new Error('Ollama API调用失败');
      }
    } catch (error) {
      console.error('Ollama API调用错误:', error);
      throw error;
    }
  }

  // 调用HuggingFace免费API
  async callHuggingFace(messages, options = {}) {
    const config = this.getAIConfig();

    try {
      // HuggingFace Inference API (免费但有限制)
      const prompt = messages[messages.length - 1]?.content || '';

      const response = await this.ctx.curl(`https://api-inference.huggingface.co/models/${config.huggingfaceModel}`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${config.apiKey}`,
          'Content-Type': 'application/json'
        },
        data: {
          inputs: prompt,
          parameters: {
            max_length: options.maxTokens || 1000,
            temperature: options.temperature || 0.7,
            return_full_text: false
          }
        },
        dataType: 'json',
        timeout: 30000
      });

      if (response.status === 200 && response.data?.[0]?.generated_text) {
        return response.data[0].generated_text;
      } else {
        throw new Error('HuggingFace API调用失败');
      }
    } catch (error) {
      console.error('HuggingFace API调用错误:', error);
      throw error;
    }
  }

  // 本地规则引擎（完全免费，无需网络）
  async callLocalEngine(messages) {
    const lastMessage = messages[messages.length - 1]?.content || '';

    // 基于规则的本地AI分析
    return this.generateLocalAnalysis(lastMessage);
  }

  // 生成本地智能分析
  generateLocalAnalysis(prompt) {
    console.log('🏠 本地引擎分析提示词:', prompt.substring(0, 200));

    // 检查是否是搭配推荐请求
    if (prompt.includes('衣柜清单') || prompt.includes('搭配推荐') || prompt.includes('基于真实衣柜')) {
      console.log('🎯 检测到搭配推荐请求，生成搭配方案');
      return this.generateLocalOutfitRecommendations(prompt);
    }

    // 分析关键词
    const keywords = this.extractKeywords(prompt);

    if (keywords.includes('搭配分析') || keywords.includes('推荐')) {
      return this.generateOutfitAnalysis(keywords, prompt);
    }

    if (keywords.includes('风格') || keywords.includes('个人')) {
      return this.generateStyleAnalysis(keywords, prompt);
    }

    if (keywords.includes('颜色') || keywords.includes('配色')) {
      return this.generateColorAnalysis(keywords, prompt);
    }

    if (keywords.includes('天气') || keywords.includes('季节')) {
      return this.generateWeatherAnalysis(keywords, prompt);
    }

    return this.generateGeneralAnalysis(keywords, prompt);
  }

  // 生成本地搭配推荐（可解析格式）
  generateLocalOutfitRecommendations(prompt) {
    console.log('🎨 本地引擎生成搭配推荐');

    // 从提示词中提取真实的衣服ID
    const clothingIds = this.extractClothingIdsFromPrompt(prompt);
    console.log('📦 提取到的衣服ID:', clothingIds);

    return `基于您的衣柜，为您推荐以下搭配：

搭配方案一：经典休闲风
- 上装：白色基础T恤 (ID:${clothingIds.tshirt || 1})
- 下装：深蓝色直筒牛仔裤 (ID:${clothingIds.jeans || 4})
- 鞋子：运动鞋 (ID:${clothingIds.sneakers || clothingIds.shoes || 7})
- 搭配理由：经典白T+牛仔裤组合，简约舒适，适合日常穿着
- 适用场合：日常出行、朋友聚会、休闲购物

搭配方案二：商务休闲风
- 上装：蓝色条纹衬衫 (ID:${clothingIds.shirt || 2})
- 下装：黑色阔腿裤 (ID:${clothingIds.pants || 5})
- 鞋子：皮鞋 (ID:${clothingIds.dress_shoes || clothingIds.shoes || 8})
- 搭配理由：蓝色衬衫搭配黑色裤子，简约大方，适合工作场合
- 适用场合：工作、商务会议、正式场合

搭配方案三：温暖舒适风
- 上装：灰色羊毛毛衣 (ID:${clothingIds.sweater || 3})
- 下装：深蓝色直筒牛仔裤 (ID:${clothingIds.jeans || 4})
- 外套：夹克 (ID:${clothingIds.jacket || clothingIds.outerwear || 6})
- 搭配理由：毛衣保暖舒适，搭配牛仔裤休闲自然
- 适用场合：秋冬季节、居家休闲、温馨约会`;
  }

  // 从提示词中提取衣服ID
  extractClothingIdsFromPrompt(prompt) {
    const ids = {};
    const lines = prompt.split('\n');

    for (const line of lines) {
      if (line.includes('ID:')) {
        const match = line.match(/ID:(\d+)/);
        if (match) {
          const id = parseInt(match[1]);

          // 根据衣服名称分类
          if (line.includes('T恤') || line.includes('t恤')) {
            ids.tshirt = id;
          } else if (line.includes('衬衫')) {
            ids.shirt = id;
          } else if (line.includes('毛衣')) {
            ids.sweater = id;
          } else if (line.includes('牛仔裤')) {
            ids.jeans = id;
          } else if (line.includes('阔腿裤') || line.includes('休闲裤')) {
            ids.pants = id;
          } else if (line.includes('夹克') || line.includes('外套')) {
            ids.jacket = id;
            ids.outerwear = id;
          } else if (line.includes('运动鞋')) {
            ids.sneakers = id;
            ids.shoes = id;
          } else if (line.includes('皮鞋')) {
            ids.dress_shoes = id;
            if (!ids.shoes) ids.shoes = id;
          }
        }
      }
    }

    return ids;
  }

  // 提取关键词
  extractKeywords(text) {
    const keywords = [];

    // 风格关键词
    const styleWords = ['休闲', '正式', '商务', '运动', '甜美', '酷帅', '文艺', '简约', '复古', '时尚'];
    const colorWords = ['黑色', '白色', '红色', '蓝色', '绿色', '黄色', '紫色', '粉色', '灰色', '棕色'];
    const weatherWords = ['晴天', '雨天', '多云', '寒冷', '炎热', '温暖', '凉爽'];
    const occasionWords = ['上班', '约会', '聚会', '运动', '旅行', '居家', '正式场合'];

    [...styleWords, ...colorWords, ...weatherWords, ...occasionWords].forEach(word => {
      if (text.includes(word)) {
        keywords.push(word);
      }
    });

    return keywords;
  }

  // 生成搭配分析
  generateOutfitAnalysis(keywords, prompt) {
    const analysis = [];

    analysis.push('🎯 **智能搭配分析**\n');

    // 基于关键词生成建议
    if (keywords.includes('休闲')) {
      analysis.push('✨ **休闲风格搭配建议**：');
      analysis.push('• 上装：选择舒适的T恤、卫衣或休闲衬衫');
      analysis.push('• 下装：牛仔裤、休闲裤或运动裤');
      analysis.push('• 鞋子：运动鞋、帆布鞋或休闲鞋');
      analysis.push('• 配饰：简约的手表、背包或帽子\n');
    }

    if (keywords.includes('正式') || keywords.includes('商务')) {
      analysis.push('💼 **商务正式搭配建议**：');
      analysis.push('• 上装：白色或浅色衬衫，深色西装外套');
      analysis.push('• 下装：西装裤或正式长裤');
      analysis.push('• 鞋子：皮鞋或正装鞋');
      analysis.push('• 配饰：领带、手表、公文包\n');
    }

    // 颜色搭配建议
    const colors = keywords.filter(k => ['黑色', '白色', '红色', '蓝色', '绿色', '黄色', '紫色', '粉色', '灰色', '棕色'].includes(k));
    if (colors.length > 0) {
      analysis.push('🎨 **颜色搭配建议**：');
      colors.forEach(color => {
        const suggestions = this.getColorMatchingSuggestions(color);
        analysis.push(`• ${color}：${suggestions}`);
      });
      analysis.push('');
    }

    // 季节建议
    analysis.push('🌤️ **季节适配建议**：');
    analysis.push('• 春季：轻薄外套 + 长袖内搭 + 长裤');
    analysis.push('• 夏季：短袖 + 短裤/裙子 + 凉鞋');
    analysis.push('• 秋季：毛衣/卫衣 + 外套 + 长裤');
    analysis.push('• 冬季：厚外套 + 保暖内搭 + 长裤 + 靴子\n');

    analysis.push('💡 **搭配小贴士**：');
    analysis.push('• 遵循"上松下紧"或"上紧下松"的搭配原则');
    analysis.push('• 全身颜色不超过3种，保持整体协调');
    analysis.push('• 根据场合选择合适的风格和正式程度');
    analysis.push('• 配饰可以为整体造型增加亮点');

    return analysis.join('\n');
  }

  // 生成风格分析
  generateStyleAnalysis(keywords, prompt) {
    const analysis = [];

    analysis.push('👤 **个人风格分析**\n');

    analysis.push('🔍 **风格识别**：');
    if (keywords.includes('休闲')) {
      analysis.push('• 您偏好休闲舒适的穿搭风格');
      analysis.push('• 注重实用性和舒适度');
      analysis.push('• 适合日常生活和轻松场合');
    } else if (keywords.includes('正式')) {
      analysis.push('• 您偏好正式商务的穿搭风格');
      analysis.push('• 注重专业形象和得体感');
      analysis.push('• 适合工作和正式场合');
    } else {
      analysis.push('• 您的风格较为多元化');
      analysis.push('• 建议根据不同场合调整穿搭');
    }

    analysis.push('\n📈 **风格建议**：');
    analysis.push('• 建立基础衣柜：黑白灰基础色单品');
    analysis.push('• 投资经典款式：不易过时的设计');
    analysis.push('• 适当尝试新元素：跟上时尚趋势');
    analysis.push('• 注重质量：选择面料和做工好的衣服');

    analysis.push('\n🎯 **改进方向**：');
    analysis.push('• 增加搭配的层次感和丰富度');
    analysis.push('• 尝试不同的颜色组合');
    analysis.push('• 添加合适的配饰提升造型');
    analysis.push('• 根据身材特点选择最适合的版型');

    return analysis.join('\n');
  }

  // 生成颜色分析
  generateColorAnalysis(keywords, prompt) {
    const analysis = [];

    analysis.push('🎨 **颜色搭配分析**\n');

    analysis.push('🌈 **基础配色原理**：');
    analysis.push('• 同色系搭配：选择同一色系的不同深浅');
    analysis.push('• 对比色搭配：选择色轮上相对的颜色');
    analysis.push('• 邻近色搭配：选择色轮上相邻的颜色');
    analysis.push('• 三角色搭配：选择色轮上等距的三种颜色\n');

    analysis.push('✨ **经典配色方案**：');
    analysis.push('• 黑白配：永不过时的经典组合');
    analysis.push('• 蓝白配：清新自然的海洋风');
    analysis.push('• 驼色配：温暖优雅的大地色系');
    analysis.push('• 红黑配：强烈对比的时尚感\n');

    analysis.push('💡 **配色建议**：');
    analysis.push('• 全身主色调不超过3种');
    analysis.push('• 用中性色作为基础，亮色作点缀');
    analysis.push('• 考虑肤色选择最适合的颜色');
    analysis.push('• 根据场合选择合适的颜色搭配');

    return analysis.join('\n');
  }

  // 生成天气分析
  generateWeatherAnalysis(keywords, prompt) {
    const analysis = [];

    analysis.push('🌤️ **天气穿搭分析**\n');

    if (keywords.includes('晴天')) {
      analysis.push('☀️ **晴天穿搭建议**：');
      analysis.push('• 选择透气性好的面料');
      analysis.push('• 可以选择亮色系增加活力');
      analysis.push('• 注意防晒，可搭配帽子或防晒衣');
    }

    if (keywords.includes('雨天')) {
      analysis.push('🌧️ **雨天穿搭建议**：');
      analysis.push('• 选择防水或快干面料');
      analysis.push('• 避免浅色容易显脏的衣服');
      analysis.push('• 搭配雨靴或防水鞋');
    }

    if (keywords.includes('寒冷')) {
      analysis.push('❄️ **寒冷天气建议**：');
      analysis.push('• 采用层次穿搭法保暖');
      analysis.push('• 选择保暖性好的面料');
      analysis.push('• 注意保护头部、手部和脚部');
    }

    analysis.push('\n🌡️ **温度穿搭指南**：');
    analysis.push('• 5°C以下：厚外套+毛衣+长裤+靴子');
    analysis.push('• 5-15°C：外套+长袖+长裤+运动鞋');
    analysis.push('• 15-25°C：薄外套+长袖/短袖+长裤');
    analysis.push('• 25°C以上：短袖+短裤/裙子+凉鞋');

    return analysis.join('\n');
  }

  // 生成通用分析
  generateGeneralAnalysis(keywords, prompt) {
    return `🤖 **智能穿搭助手**

感谢您使用智能穿搭分析功能！

🎯 **个性化建议**：
• 根据您的衣柜建立个人风格档案
• 结合天气和场合提供搭配建议
• 学习您的偏好持续优化推荐

💡 **使用建议**：
• 尝试不同的搭配组合
• 记录您喜欢的搭配方案
• 定期更新衣柜信息

🌟 **功能特色**：
• 本地智能分析，保护隐私
• 专业的时尚搭配建议
• 持续学习优化推荐算法

如需更详细的分析，请描述具体的搭配需求或风格偏好！`;
  }

  // 获取颜色搭配建议
  getColorMatchingSuggestions(color) {
    const colorMap = {
      '黑色': '可搭配任何颜色，经典百搭',
      '白色': '纯净百搭，可与任何颜色组合',
      '红色': '搭配黑色、白色、牛仔蓝显得经典',
      '蓝色': '搭配白色、米色、红色很协调',
      '绿色': '搭配白色、米色、棕色很自然',
      '黄色': '搭配蓝色、紫色、白色很亮眼',
      '紫色': '搭配白色、黄色、银色很优雅',
      '粉色': '搭配白色、灰色、蓝色很温柔',
      '灰色': '中性色，可与任何颜色搭配',
      '棕色': '搭配米色、白色、橙色很温暖'
    };

    return colorMap[color] || '建议与基础色搭配';
  }

  // 统一的AI调用接口
  async callAI(messages, options = {}) {
    const config = this.getAIConfig();

    console.log(`🤖 AI调用开始 - 提供商: ${config.provider}`);
    console.log(`🔑 API密钥状态: ${config.deepseekApiKey ? '已配置' : '未配置'}`);

    try {
      switch (config.provider) {
        case 'local':
          return await this.callLocalEngine(messages);

        case 'qianwen':
          // 通义千问 - 免费额度
          if (config.qianwenApiKey && config.qianwenApiKey !== 'your_qianwen_key') {
            return await this.callQianwen(messages, options);
          }
          console.log('通义千问API密钥未配置，使用本地引擎');
          return await this.callLocalEngine(messages);

        case 'deepseek':
          // DeepSeek - 免费额度
          console.log(`🔑 DeepSeek API密钥: ${config.deepseekApiKey ? '已配置' : '未配置'}`);
          if (config.deepseekApiKey && config.deepseekApiKey !== 'your_deepseek_key') {
            console.log('📞 调用DeepSeek API...');
            return await this.callDeepSeek(messages, options);
          }
          console.log('⚠️ DeepSeek API密钥未配置，使用本地引擎');
          return await this.callLocalEngine(messages);

        case 'doubao':
          // 豆包 - 原始豆包API
          console.log(`🔑 豆包API密钥: ${config.doubaoApiKey ? '已配置' : '未配置'}`);
          if (config.doubaoApiKey && config.doubaoApiKey !== 'your_doubao_key') {
            console.log('📞 调用豆包API...');
            return await this.callDoubao(messages, options);
          }
          console.log('⚠️ 豆包API密钥未配置，使用本地引擎');
          return await this.callLocalEngine(messages);

        case 'volcano':
          // 火山引擎火山方舟
          console.log(`🔑 火山引擎API密钥: ${config.volcanoApiKey ? '已配置' : '未配置'}`);
          if (config.volcanoApiKey && config.volcanoApiKey !== 'your_volcano_key') {
            console.log('🌋 调用火山引擎API...');
            return await this.callVolcano(messages, options);
          }
          console.log('⚠️ 火山引擎API密钥未配置，使用本地引擎');
          return await this.callLocalEngine(messages);

        case 'vapi':
          // V-API聚合服务
          if (config.vapiKey && config.vapiKey !== 'your_vapi_key') {
            return await this.callVAPI(messages, options);
          }
          console.log('V-API密钥未配置，使用本地引擎');
          return await this.callLocalEngine(messages);

        case 'ollama':
          return await this.callOllama(messages, options);

        case 'huggingface':
          if (config.apiKey && config.apiKey !== 'your_api_key') {
            return await this.callHuggingFace(messages, options);
          }
          return await this.callLocalEngine(messages);

        case 'openai':
          if (config.apiKey && config.apiKey !== 'your_api_key') {
            return await this.callOpenAI(messages, options);
          }
          return await this.callLocalEngine(messages);

        case 'zhipu':
          if (config.apiKey && config.apiKey !== 'your_api_key') {
            return await this.callZhipu(messages, options);
          }
          return await this.callLocalEngine(messages);

        default:
          console.log(`未知的AI提供商: ${config.provider}，使用本地引擎`);
          return await this.callLocalEngine(messages);
      }
    } catch (error) {
      console.error('AI调用失败，使用本地引擎:', error);
      return await this.callLocalEngine(messages);
    }
  }

  // 模拟AI响应（用于测试和降级）
  getMockAIResponse(messages) {
    const lastMessage = messages[messages.length - 1]?.content || '';
    
    if (lastMessage.includes('搭配分析')) {
      return `基于您的衣柜分析：
1. 您的衣柜以休闲风格为主，适合日常穿着
2. 建议增加一些正式场合的服装
3. 颜色搭配建议：黑白灰为基础色，可以添加一些亮色点缀
4. 当前天气适合穿着轻薄的春季服装
5. 推荐搭配：白色衬衫 + 深色牛仔裤 + 小白鞋`;
    }
    
    if (lastMessage.includes('风格建议')) {
      return `个人风格建议：
1. 根据您的穿搭历史，您偏好简约休闲风格
2. 建议尝试更多层次搭配，增加造型丰富度
3. 可以考虑添加一些配饰来提升整体效果
4. 颜色方面建议保持简洁，以基础色为主`;
    }
    
    return '感谢您的咨询，我会根据您的衣柜和偏好为您提供个性化的搭配建议。';
  }

  // 智能搭配分析（基于真实衣柜）
  async analyzeOutfitRecommendation(userProfile, weatherInfo, clothingItems, options = {}) {
    const { occasion, requestId } = options;
    console.log(`🎯 开始AI搭配分析，衣柜中有${clothingItems.length}件衣服，请求ID: ${requestId}`);

    // 如果没有衣服，返回购买建议
    if (clothingItems.length === 0) {
      console.log('⚠️ 用户衣柜为空，返回购买建议');
      return this.generateShoppingRecommendation(weatherInfo);
    }

    // 🔥 根据天气预筛选合适的衣服，减少token消耗
    let suitableClothing = this.filterClothingByWeather(clothingItems, weatherInfo);
    console.log(`🌤️ 根据${weatherInfo.temperature}°C ${weatherInfo.condition}天气，从${clothingItems.length}件衣服中筛选出${suitableClothing.length}件合适的衣服`);

    // 最多只传6-8件衣服到大模型
    if (suitableClothing.length > 8) {
      suitableClothing = suitableClothing.slice(0, 8);
      console.log(`⚡ 已截断衣服数量，只传递前${suitableClothing.length}件到大模型`);
    }

    // 打印筛选后的衣服样例
    if (suitableClothing.length > 0) {
      console.log('📦 筛选后衣服样例:', suitableClothing.map(item => ({
        id: item.id,
        name: item.name,
        color: item.color,
        category: item.category?.name,
        season: item.season
      })));
    }

    // 如果筛选后没有合适的衣服，使用全部衣服
    const finalClothingList = suitableClothing.length > 0 ? suitableClothing : clothingItems;

    // 日志监控：打印最终传给大模型的衣服数量和ID
    console.log(`🟢 最终传给大模型的衣服数量: ${finalClothingList.length}`);
    console.log('🟢 衣服ID列表:', finalClothingList.map(item => item.id));

    console.log('🏗️ 构建AI提示词...');
    const prompt = this.buildOutfitAnalysisPrompt(userProfile, weatherInfo, finalClothingList, { occasion, requestId });
    console.log(`📝 提示词长度: ${prompt.length} 字符`);
    console.log(`📝 提示词预览: ${prompt.substring(0, 300)}...`);

    const messages = [
      {
        role: 'system',
        content: `你是一位专业的时尚搭配师。用户会提供他们衣柜中的真实衣服清单，请基于这些现有衣服为他们搭配出完整的造型。\n\n要求：\n1) 只用用户提供的衣服，使用准确ID号\n2) 给出2-3套不同搭配组合\n3) 严格按照以下格式回答：\n\n搭配方案一：[风格名称]\n- 上装：[衣服名称] (ID:[数字])\n- 下装：[衣服名称] (ID:[数字])\n- 鞋子：[衣服名称] (ID:[数字])\n- 理由：[简要理由]\n- 场合：[场合描述]\n\n搭配方案二：[风格名称]\n...\n\n不要有任何前言或分析。`
      },
      {
        role: 'user',
        content: prompt
      }
    ];

    try {
      console.log('🚀 开始调用AI...');
      // max_tokens默认256-512
      const response = await this.callAI(messages, { maxTokens: 384, temperature: 0.7 });
      console.log(`✅ AI响应成功，长度: ${response.length} 字符`);
      console.log(`📄 AI响应内容: ${response.substring(0, 500)}...`);

      console.log('🔍 开始解析AI响应...');

      try {
        // 检查AI是否按照要求的格式回答
        if (response.includes('搭配方案一') && response.includes('ID:')) {
          console.log('✅ AI按照要求格式回答，直接解析搭配方案');
          const parsed = this.parseOutfitAnalysis(response, clothingItems);
          if (parsed.recommendations && parsed.recommendations.length > 0) {
            console.log(`📊 成功解析: ${parsed.recommendations.length} 个推荐`);
            return {
              recommendations: parsed.recommendations,
              analysis: response,
              source: 'AI直接搭配',
              isRealClothing: true
            };
          }
        }

        // AI返回的是风格分析，需要转换为具体搭配推荐
        console.log('🎨 AI返回风格分析，转换为具体搭配推荐');
        const aiStyleAnalysis = response;

        // 基于AI分析和真实衣柜生成具体搭配
        const recommendations = this.generateRecommendationsFromAIAnalysis(aiStyleAnalysis, clothingItems, weatherInfo, userProfile);

        console.log(`📊 基于AI分析生成: ${recommendations.length} 个推荐`);
        console.log('🎉 AI分析成功完成');

        const result = {
          recommendations,
          analysis: aiStyleAnalysis,
          source: 'AI分析',
          isRealClothing: true
        };

        // 🔥 保存AI推荐到数据库
        await this.saveAIRecommendations(userProfile.id, result, weatherInfo, options);

        return result;
      } catch (parseError) {
        console.error('❌ AI响应解析失败:', parseError.message);
        console.log('🔄 AI调用成功但解析失败，使用智能降级');
        // AI调用成功但解析失败，使用智能降级，并保留AI分析结果
        const fallbackResult = this.generateSmartFallbackRecommendations(clothingItems, weatherInfo, userProfile, { occasion, requestId });
        fallbackResult.analysis = response; // 保留AI的原始分析
        fallbackResult.source = 'AI分析+智能降级';
        return fallbackResult;
      }
    } catch (error) {
      console.error('❌ AI调用失败:', error.message);
      console.error('❌ 错误详情:', error);
      console.log('🔄 使用智能降级生成推荐');
      return this.generateSmartFallbackRecommendations(clothingItems, weatherInfo, userProfile, { occasion, requestId });
    }
  }

  // 生成购买建议（当衣柜为空时）
  generateShoppingRecommendation(weatherInfo) {
    return {
      recommendations: [],
      analysis: `您的衣柜还没有衣服呢！建议先添加一些基础单品：

🛍️ **基础衣柜建议**：
• 上装：白色T恤、蓝色衬衫、黑色卫衣
• 下装：深色牛仔裤、黑色休闲裤
• 外套：牛仔外套或薄款外套
• 鞋子：白色运动鞋、黑色休闲鞋

根据当前天气（${weatherInfo.temperature}°C），建议优先购买适合的季节性单品。

添加衣服后，AI就能为您生成个性化的搭配推荐了！`,
      source: '购买建议'
    };
  }

  // 构建搭配分析提示词（基于真实衣柜）
  buildOutfitAnalysisPrompt(userProfile, weatherInfo, clothingItems, options = {}) {
    const { occasion, requestId } = options;
    // 按分类整理衣服
    const clothingByCategory = {};
    clothingItems.forEach(item => {
      const category = item.category?.name || '其他';
      if (!clothingByCategory[category]) {
        clothingByCategory[category] = [];
      }
      clothingByCategory[category].push({
        id: item.id,
        name: item.name,
        color: item.color || '未知'
      });
    });

    // 生成衣服清单（只保留必要字段）
    let clothingInventory = '用户衣柜清单：\n';
    Object.keys(clothingByCategory).forEach(category => {
      clothingInventory += `\n【${category}】\n`;
      clothingByCategory[category].forEach((item, index) => {
        clothingInventory += `${index + 1}. ${item.name} (ID:${item.id}, 颜色:${item.color})\n`;
      });
    });

    return `任务：基于下方真实衣柜，推荐2-3套适合${occasion || '当前场合'}的完整穿搭。\n${clothingInventory}\n当前天气：${weatherInfo.temperature || 20}°C，${weatherInfo.condition || '晴'}\n要求：只用清单里的衣服，输出格式如下：\n\n搭配方案一：[风格]\n- 上装：[名称] (ID:xx)\n- 下装：[名称] (ID:xx)\n- 鞋子：[名称] (ID:xx)\n- 理由：[简要理由]\n- 场合：[场合]\n\n搭配方案二：...\n\n不要有任何前言、分析或总结。`;
  }

  // 解析AI分析结果（基于真实衣柜）
  parseOutfitAnalysis(response, clothingItems = []) {
    console.log('开始解析AI搭配分析结果...');

    try {
      // 尝试解析JSON格式的响应
      const jsonMatch = response.match(/\{[\s\S]*\}/);
      if (jsonMatch) {
        const parsed = JSON.parse(jsonMatch[0]);
        if (parsed.recommendations) {
          return this.enrichRecommendationsWithClothingData(parsed, clothingItems);
        }
      }
    } catch (error) {
      console.log('JSON解析失败，使用文本解析');
    }

    // 使用文本解析，专门处理基于真实衣柜的推荐
    return this.parseClothingBasedResponse(response, clothingItems);
  }

  // 为推荐结果补充真实衣服数据
  enrichRecommendationsWithClothingData(parsed, clothingItems) {
    const clothingMap = {};
    clothingItems.forEach(item => {
      clothingMap[item.id] = item;
    });

    parsed.recommendations = parsed.recommendations.map(rec => {
      // 如果推荐中有clothingIds，补充完整的衣服信息
      if (rec.clothingIds && rec.clothingIds.length > 0) {
        rec.items = rec.clothingIds.map(id => {
          const item = clothingMap[id];
          return item ? this.formatClothingItem(item) : null;
        }).filter(Boolean);
      }

      return {
        ...rec,
        source: 'AI分析',
        isRealClothing: true
      };
    });

    return parsed;
  }

  // 解析基于真实衣柜的文本响应
  parseClothingBasedResponse(response, clothingItems) {
    console.log('解析基于真实衣柜的AI响应...');

    const recommendations = [];
    const clothingMap = {};

    // 建立衣服ID映射
    clothingItems.forEach(item => {
      clothingMap[item.id] = item;
      clothingMap[item.name] = item; // 也支持按名称查找
    });

    // 按搭配方案分割
    const outfitSections = response.split(/搭配方案[一二三四五]|方案[一二三四五]|搭配[一二三四五]/);

    outfitSections.forEach((section, index) => {
      if (index === 0 || section.trim().length < 10) return; // 跳过标题部分

      const outfit = this.parseOutfitSection(section, clothingMap);
      if (outfit && outfit.items.length > 0) {
        recommendations.push(outfit);
      }
    });

    // 如果没有解析到搭配，尝试简单解析
    if (recommendations.length === 0) {
      const simpleOutfit = this.parseSimpleOutfit(response, clothingMap);
      if (simpleOutfit) {
        recommendations.push(simpleOutfit);
      }
    }

    return {
      recommendations: recommendations.slice(0, 3),
      analysis: response,
      source: 'AI分析',
      isRealClothing: true
    };
  }

  // 解析单个搭配方案
  parseOutfitSection(section, clothingMap) {
    const lines = section.split('\n').map(line => line.trim()).filter(line => line.length > 0);

    const outfit = {
      items: [],
      clothingIds: [],
      reason: '',
      score: 0.85,
      tags: ['AI推荐', '真实衣柜'],
      isRealClothing: true
    };

    let styleName = '';
    let reason = '';
    let occasion = '';

    lines.forEach(line => {
      // 提取风格名称
      if (line.includes('：') && !line.includes('上装') && !line.includes('下装') && !line.includes('外套') && !line.includes('鞋子')) {
        if (line.includes('搭配理由')) {
          reason = line.split('：')[1] || '';
        } else if (line.includes('适用场合')) {
          occasion = line.split('：')[1] || '';
        } else if (!styleName) {
          styleName = line.split('：')[0] || '';
        }
      }

      // 提取衣服信息
      const clothingMatch = line.match(/ID:(\d+)|ID:\s*(\d+)/);
      if (clothingMatch) {
        const clothingId = parseInt(clothingMatch[1] || clothingMatch[2]);
        const clothing = clothingMap[clothingId];

        if (clothing) {
          outfit.items.push(this.formatClothingItem(clothing));
          outfit.clothingIds.push(clothingId);
        }
      } else {
        // 尝试按名称匹配
        Object.keys(clothingMap).forEach(key => {
          if (typeof key === 'string' && line.includes(key) && !outfit.clothingIds.includes(clothingMap[key].id)) {
            outfit.items.push(this.formatClothingItem(clothingMap[key]));
            outfit.clothingIds.push(clothingMap[key].id);
          }
        });
      }
    });

    // 构建推荐理由
    outfit.reason = styleName || '智能搭配';
    if (reason) outfit.reason += ` - ${reason}`;
    if (occasion) outfit.reason += ` 适合${occasion}`;

    return outfit.items.length > 0 ? outfit : null;
  }

  // 简单解析（降级方案）
  parseSimpleOutfit(response, clothingMap) {
    const outfit = {
      items: [],
      clothingIds: [],
      reason: 'AI智能搭配建议',
      score: 0.8,
      tags: ['AI推荐'],
      isRealClothing: true
    };

    // 查找所有提到的衣服ID
    const idMatches = response.match(/ID:(\d+)/g);
    if (idMatches) {
      idMatches.forEach(match => {
        const id = parseInt(match.replace('ID:', ''));
        const clothing = clothingMap[id];
        if (clothing && !outfit.clothingIds.includes(id)) {
          outfit.items.push(this.formatClothingItem(clothing));
          outfit.clothingIds.push(id);
        }
      });
    }

    return outfit.items.length > 0 ? outfit : null;
  }

  // 解析文本响应（保留原方法作为降级）
  parseTextResponse(response) {
    const recommendations = [];
    const lines = response.split('\n');

    let currentRec = null;

    lines.forEach(line => {
      line = line.trim();
      if (line.includes('搭配') && line.includes('：')) {
        if (currentRec) {
          recommendations.push(currentRec);
        }
        currentRec = {
          items: [],
          reason: line,
          score: 0.8,
          tags: ['AI推荐']
        };
      } else if (currentRec && line.length > 0) {
        currentRec.reason += ' ' + line;
      }
    });

    if (currentRec) {
      recommendations.push(currentRec);
    }

    return {
      recommendations: recommendations.slice(0, 3),
      analysis: response,
      source: 'AI分析'
    };
  }

  // 个人风格分析
  async analyzePersonalStyle(userWearHistory, clothingItems) {
    const prompt = `请分析用户的个人穿搭风格：

穿搭历史：
${userWearHistory.map(record => 
  `${record.wear_date}: ${record.outfit?.name || '未知搭配'}`
).join('\n')}

衣柜统计：
${clothingItems.map(item => 
  `${item.category?.name || '未分类'}: ${item.name} (${item.color || '未知'})`
).join('\n')}

请分析：
1. 用户的主要风格倾向
2. 颜色偏好
3. 搭配习惯
4. 改进建议
5. 推荐购买的单品类型`;

    const messages = [
      {
        role: 'system',
        content: '你是一位专业的时尚分析师，擅长分析个人穿搭风格和提供改进建议。'
      },
      {
        role: 'user',
        content: prompt
      }
    ];

    return await this.callAI(messages);
  }

  // 智能降级推荐（当AI失败时）
  generateSmartFallbackRecommendations(clothingItems, weatherInfo, userProfile, options = {}) {
    const { occasion, requestId } = options;
    console.log(`🔄 生成智能降级推荐... 请求ID: ${requestId}`);

    const recommendations = [];

    // 按分类整理衣服
    const clothingByCategory = {};
    clothingItems.forEach(item => {
      const category = item.category?.name || '其他';
      if (!clothingByCategory[category]) {
        clothingByCategory[category] = [];
      }
      clothingByCategory[category].push(item);
    });

    console.log('📦 衣服分类:', Object.keys(clothingByCategory).map(key => `${key}: ${clothingByCategory[key].length}件`));

    // 获取各类衣服
    const tops = clothingByCategory['上装'] || [];
    const bottoms = clothingByCategory['下装'] || [];
    const outerwear = clothingByCategory['外套'] || [];
    const shoes = clothingByCategory['鞋子'] || [];

    // 生成多样化的搭配方案
    const strategies = [
      { name: '经典搭配', priority: ['黑色', '白色', '灰色', '深蓝'] },
      { name: '时尚潮流', priority: ['红色', '黄色', '绿色', '紫色'] },
      { name: '舒适休闲', priority: ['棉', '针织', '运动'] },
      { name: '场合适宜', priority: [] }
    ];

    const maxOutfits = Math.min(5, Math.max(tops.length, bottoms.length));
    const usedCombinations = new Set();

    for (let i = 0; i < maxOutfits; i++) {
      const strategy = strategies[i % strategies.length];
      const outfit = {
        clothingIds: [],
        items: [],
        score: 0.8 + (Math.random() * 0.15), // 随机化分数
        tags: ['智能推荐', '真实衣柜', strategy.name],
        isRealClothing: true,
        reason: '',
        strategy: strategy.name,
        requestId,
        timestamp: Date.now() + i
      };

      // 智能选择上装
      if (tops.length > 0) {
        const top = this.selectItemByStrategy(tops, strategy, i);
        if (top) {
          outfit.items.push(this.formatClothingItem(top));
          outfit.clothingIds.push(top.id);
        }
      }

      // 智能选择下装
      if (bottoms.length > 0) {
        const bottom = this.selectItemByStrategy(bottoms, strategy, i);
        if (bottom) {
          outfit.items.push(this.formatClothingItem(bottom));
          outfit.clothingIds.push(bottom.id);
        }
      }

      // 根据天气和策略添加外套
      if ((weatherInfo.temperature < 20 || strategy.name === '经典搭配') && outerwear.length > 0) {
        const outer = this.selectItemByStrategy(outerwear, strategy, i);
        if (outer) {
          outfit.items.push(this.formatClothingItem(outer));
          outfit.clothingIds.push(outer.id);
        }
      }

      // 添加鞋子
      if (shoes.length > 0) {
        const shoe = this.selectItemByStrategy(shoes, strategy, i);
        if (shoe) {
          outfit.items.push(this.formatClothingItem(shoe));
          outfit.clothingIds.push(shoe.id);
        }
      }

      // 检查组合是否重复
      const combinationKey = outfit.clothingIds.sort().join(',');
      if (!usedCombinations.has(combinationKey) && outfit.items.length >= 2) {
        usedCombinations.add(combinationKey);

        // 生成搭配理由
        outfit.reason = this.generateSmartOutfitReason(outfit.items, weatherInfo, strategy, occasion);
        recommendations.push(outfit);
      }
    }

    return {
      recommendations,
      analysis: `基于您的${clothingItems.length}件衣服生成了${recommendations.length}套个性化搭配推荐。

🎯 **智能分析**：
• 您的衣柜包含：${Object.keys(clothingByCategory).join('、')}
• 当前天气：${weatherInfo.temperature}°C ${weatherInfo.condition}
• 推荐风格：${userProfile.preferredStyle || '休闲'}
• 场合需求：${occasion || '日常生活'}

💡 **搭配策略**：
• 经典搭配：永不过时的经典组合
• 时尚潮流：彰显个性的时尚搭配
• 舒适休闲：轻松自在的日常穿搭
• 场合适宜：得体大方的正式搭配

🌟 **个性化特色**：
• 每套搭配都基于您的真实衣柜
• 考虑了当前天气和场合需求
• 融合了多种风格策略
• 避免重复，每次都有新的组合`,
      source: '智能推荐引擎',
      isRealClothing: true
    };
  }

  // 根据策略选择单品
  selectItemByStrategy(items, strategy, index) {
    if (items.length === 0) return null;

    let selectedItem;
    const priorities = strategy.priority || [];

    // 根据策略优先级选择
    for (const priority of priorities) {
      selectedItem = items.find(item =>
        item.color?.includes(priority) ||
        item.name?.includes(priority) ||
        item.description?.includes(priority)
      );
      if (selectedItem) break;
    }

    // 如果没有找到优先级匹配的，使用轮换选择
    if (!selectedItem) {
      selectedItem = items[index % items.length];
    }

    return selectedItem;
  }

  // 生成智能搭配理由
  generateSmartOutfitReason(items, weatherInfo, strategy, occasion) {
    const reasons = [];

    // 策略相关理由
    switch (strategy.name) {
      case '经典搭配':
        reasons.push('经典百搭，永不过时');
        break;
      case '时尚潮流':
        reasons.push('时尚前卫，彰显个性');
        break;
      case '舒适休闲':
        reasons.push('舒适自在，轻松惬意');
        break;
      case '场合适宜':
        reasons.push('得体大方，场合适宜');
        break;
    }

    // 天气相关理由
    if (weatherInfo) {
      const temp = weatherInfo.temperature;
      if (temp <= 10) {
        reasons.push('保暖御寒');
      } else if (temp <= 20) {
        reasons.push('温度适宜');
      } else if (temp <= 30) {
        reasons.push('清爽舒适');
      } else {
        reasons.push('凉爽透气');
      }
    }

    // 场合相关理由
    if (occasion) {
      reasons.push(`适合${occasion}`);
    }

    // 颜色搭配理由
    const colors = items.map(item => item.color).filter(Boolean);
    if (colors.length > 1) {
      const hasNeutral = colors.some(color =>
        ['黑色', '白色', '灰色', '米色'].some(neutral => color.includes(neutral))
      );
      if (hasNeutral) {
        reasons.push('颜色协调');
      }
    }

    return reasons.join('，') || '精心搭配推荐';
  }

  // 生成搭配理由
  generateOutfitReason(items, weatherInfo, index) {
    const reasons = [];

    // 基础描述
    const styleNames = ['经典搭配', '时尚组合', '舒适搭配'];
    reasons.push(styleNames[(index - 1) % styleNames.length]);

    // 天气适配
    if (weatherInfo.temperature < 10) {
      reasons.push('保暖适宜');
    } else if (weatherInfo.temperature > 25) {
      reasons.push('清爽透气');
    } else {
      reasons.push('温度适中');
    }

    // 颜色分析
    const colors = items.map(item => item.color).filter(Boolean);
    if (colors.includes('白色') && colors.includes('蓝色')) {
      reasons.push('蓝白经典配色');
    } else if (colors.includes('黑色')) {
      reasons.push('黑色百搭');
    }

    // 风格分析
    const styles = items.map(item => item.style).filter(Boolean);
    if (styles.includes('casual')) {
      reasons.push('休闲舒适');
    } else if (styles.includes('formal')) {
      reasons.push('正式得体');
    }

    return reasons.join('，') + `，适合${weatherInfo.condition}天穿着`;
  }

  // 格式化衣服数据，确保前端能正确渲染
  formatClothingItem(item) {
    return {
      id: item.id,
      name: item.name,
      color: item.color || '未知',
      brand: item.brand || '',
      style: item.style || '',
      season: item.season || '',
      image: item.image || '',
      category: item.category ? {
        id: item.category.id,
        name: item.category.name
      } : null,
      // 添加前端渲染需要的字段
      categoryName: item.category?.name || '其他',
      displayName: `${item.name} (${item.color || '未知'})`,
      // 保留原始数据
      ...item.dataValues || {}
    };
  }

  // 基于AI风格分析生成具体搭配推荐
  generateRecommendationsFromAIAnalysis(aiAnalysis, clothingItems, weatherInfo, userProfile) {
    console.log('🎨 基于AI分析生成具体搭配推荐');

    // 按分类整理衣服
    const clothingByCategory = {};
    clothingItems.forEach(item => {
      const category = item.category?.name || '其他';
      if (!clothingByCategory[category]) {
        clothingByCategory[category] = [];
      }
      clothingByCategory[category].push(item);
    });

    console.log('📦 衣服分类:', Object.keys(clothingByCategory).map(key => `${key}: ${clothingByCategory[key].length}件`));

    // 获取各类衣服
    const tops = [...(clothingByCategory['T恤'] || []), ...(clothingByCategory['衬衫'] || []), ...(clothingByCategory['毛衣'] || []), ...(clothingByCategory['上装'] || [])];
    const bottoms = [...(clothingByCategory['牛仔裤'] || []), ...(clothingByCategory['休闲裤'] || []), ...(clothingByCategory['下装'] || [])];
    const outerwear = [...(clothingByCategory['夹克'] || []), ...(clothingByCategory['外套'] || [])];
    const shoes = [...(clothingByCategory['运动鞋'] || []), ...(clothingByCategory['皮鞋'] || []), ...(clothingByCategory['鞋子'] || [])];

    const recommendations = [];

    // 根据AI分析的风格偏好生成搭配
    const styles = this.extractStylesFromAIAnalysis(aiAnalysis);

    // 生成3套不同风格的搭配
    const outfitStyles = [
      { name: '经典休闲风', priority: ['白色', '蓝色', '深蓝色'], occasion: '日常出行、朋友聚会' },
      { name: '商务休闲风', priority: ['黑色', '灰色', '蓝色'], occasion: '工作、商务会议' },
      { name: '温暖舒适风', priority: ['灰色', '米色', '棕色'], occasion: '秋冬季节、居家休闲' }
    ];

    for (let i = 0; i < Math.min(3, outfitStyles.length); i++) {
      const style = outfitStyles[i];
      const outfit = this.createOutfitFromStyle(style, tops, bottoms, outerwear, shoes, weatherInfo, i);

      if (outfit && outfit.items.length >= 2) {
        recommendations.push(outfit);
      }
    }

    console.log(`🎯 生成了${recommendations.length}套基于AI分析的搭配推荐`);
    return recommendations;
  }

  // 从AI分析中提取风格信息
  extractStylesFromAIAnalysis(aiAnalysis) {
    const styles = [];

    if (aiAnalysis.includes('休闲')) styles.push('休闲');
    if (aiAnalysis.includes('商务')) styles.push('商务');
    if (aiAnalysis.includes('正式')) styles.push('正式');
    if (aiAnalysis.includes('运动')) styles.push('运动');
    if (aiAnalysis.includes('温暖')) styles.push('温暖');

    return styles.length > 0 ? styles : ['休闲']; // 默认休闲风格
  }

  // 根据风格创建具体搭配
  createOutfitFromStyle(style, tops, bottoms, outerwear, shoes, weatherInfo, index) {
    const outfit = {
      clothingIds: [],
      items: [],
      score: 0.9,
      tags: ['AI推荐', '真实衣柜'],
      isRealClothing: true,
      reason: ''
    };

    // 选择上装（优先选择符合风格的颜色）
    const selectedTop = this.selectItemByColorPriority(tops, style.priority);
    if (selectedTop) {
      outfit.items.push(selectedTop);
      outfit.clothingIds.push(selectedTop.id);
    }

    // 选择下装
    const selectedBottom = this.selectItemByColorPriority(bottoms, style.priority, outfit.clothingIds);
    if (selectedBottom) {
      outfit.items.push(selectedBottom);
      outfit.clothingIds.push(selectedBottom.id);
    }

    // 根据天气添加外套
    if (weatherInfo.temperature < 18 && outerwear.length > 0) {
      const selectedOuter = this.selectItemByColorPriority(outerwear, style.priority, outfit.clothingIds);
      if (selectedOuter) {
        outfit.items.push(selectedOuter);
        outfit.clothingIds.push(selectedOuter.id);
      }
    }

    // 添加鞋子
    const selectedShoe = this.selectItemByColorPriority(shoes, style.priority, outfit.clothingIds);
    if (selectedShoe) {
      outfit.items.push(selectedShoe);
      outfit.clothingIds.push(selectedShoe.id);
    }

    // 生成搭配理由
    outfit.reason = `${style.name}：${this.generateStyleReason(style, outfit.items, weatherInfo)}，适合${style.occasion}`;

    return outfit;
  }

  // 根据颜色优先级选择衣服
  selectItemByColorPriority(items, colorPriority, excludeIds = []) {
    // 过滤已选择的衣服
    const availableItems = items.filter(item => !excludeIds.includes(item.id));

    if (availableItems.length === 0) return null;

    // 按颜色优先级排序
    for (const color of colorPriority) {
      const matchingItem = availableItems.find(item =>
        item.color && item.color.includes(color)
      );
      if (matchingItem) return matchingItem;
    }

    // 如果没有匹配的颜色，返回第一个可用的
    return availableItems[0];
  }

  // 生成风格搭配理由
  generateStyleReason(style, items, weatherInfo) {
    const colors = items.map(item => item.color).filter(Boolean);

    let reason = '';

    if (colors.includes('白色') && colors.includes('蓝色')) {
      reason += '蓝白经典配色';
    } else if (colors.includes('黑色')) {
      reason += '黑色百搭经典';
    } else {
      reason += '颜色搭配和谐';
    }

    if (weatherInfo.temperature < 15) {
      reason += '，保暖适宜';
    } else if (weatherInfo.temperature > 25) {
      reason += '，清爽透气';
    } else {
      reason += '，温度适中';
    }

    return reason;
  }

  // 根据天气筛选合适的衣服（减少token消耗）
  filterClothingByWeather(clothingItems, weatherInfo) {
    const temperature = weatherInfo.temperature || 20;
    const condition = weatherInfo.condition || '晴';

    console.log(`🌡️ 开始根据天气筛选衣服：${temperature}°C ${condition}`);

    const suitableClothing = clothingItems.filter(item => {
      // 根据温度筛选季节合适的衣服
      const season = item.season || 'all';
      let temperatureSuitable = true;

      if (temperature <= 5) {
        // 严寒：只要冬季和全季节衣服
        temperatureSuitable = season === 'winter' || season === 'all';
      } else if (temperature <= 15) {
        // 寒冷：秋冬和全季节衣服
        temperatureSuitable = ['autumn', 'winter', 'all'].includes(season);
      } else if (temperature <= 25) {
        // 温和：春秋和全季节衣服
        temperatureSuitable = ['spring', 'autumn', 'all'].includes(season);
      } else {
        // 炎热：夏季和全季节衣服
        temperatureSuitable = ['summer', 'all'].includes(season);
      }

      // 根据天气条件筛选
      let weatherSuitable = true;
      if (condition.includes('雨')) {
        // 雨天：避免浅色衣服，优先深色
        const color = item.color || '';
        weatherSuitable = !['白色', '米色', '浅色'].some(lightColor => color.includes(lightColor));
      }

      return temperatureSuitable && weatherSuitable;
    });

    // 确保每个分类至少有一件衣服
    const categories = ['上装', 'T恤', '衬衫', '毛衣', '下装', '牛仔裤', '休闲裤', '鞋子', '运动鞋', '皮鞋'];
    const missingCategories = [];

    for (const category of categories) {
      const hasCategory = suitableClothing.some(item =>
        item.category?.name === category || item.name?.includes(category.replace('装', ''))
      );
      if (!hasCategory) {
        // 如果某个分类没有合适的衣服，从原始列表中添加一件
        const fallbackItem = clothingItems.find(item =>
          item.category?.name === category || item.name?.includes(category.replace('装', ''))
        );
        if (fallbackItem && !suitableClothing.find(item => item.id === fallbackItem.id)) {
          suitableClothing.push(fallbackItem);
          missingCategories.push(category);
        }
      }
    }

    if (missingCategories.length > 0) {
      console.log(`🔄 为缺失分类补充衣服：${missingCategories.join(', ')}`);
    }

    console.log(`✅ 筛选完成：${clothingItems.length} → ${suitableClothing.length} 件衣服`);
    return suitableClothing;
  }

  // 保存AI推荐到数据库
  async saveAIRecommendations(userId, result, weatherInfo, options = {}) {
    const { occasion } = options;

    try {
      console.log(`💾 开始保存AI推荐到数据库，用户ID: ${userId}`);

      const config = this.getAIConfig();
      const aiProvider = config.provider || 'local';

      // 为每个推荐创建数据库记录
      const savedRecommendations = [];

      for (const recommendation of result.recommendations) {
        const recommendationData = {
          user_id: userId,
          type: occasion ? 'occasion' : 'outfit',
          occasion: occasion || null,
          weather_info: weatherInfo,
          clothing_ids: recommendation.clothingIds || [],
          ai_provider: aiProvider,
          ai_analysis: result.analysis || null,
          recommendation_data: recommendation,
          style_tags: recommendation.tags || [],
          reason: recommendation.reason || '',
          score: recommendation.score || 0.8
        };

        const saved = await this.ctx.model.AIRecommendation.create(recommendationData);
        savedRecommendations.push(saved);

        console.log(`✅ 保存推荐成功，ID: ${saved.id}, 类型: ${saved.type}, 衣服数量: ${recommendation.clothingIds?.length || 0}`);
      }

      console.log(`🎉 共保存${savedRecommendations.length}个AI推荐`);
      return savedRecommendations;

    } catch (error) {
      console.error('❌ 保存AI推荐失败:', error);
      // 不影响主流程，只记录错误
      return [];
    }
  }
}

module.exports = AIAnalysisService;
